﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PH.Model.Schools;
namespace PH.Data.Schools
{
    public class ClassCommand
    {
        public static void SaveCheck(ClassModel cm, DBCentre db)
        {
            if (cm.CIndex == 0)
                throw new Utils.PhException("请提供班级序号（1-99的数字）");
            if (cm.SchoolGuid==Guid.Empty)
                throw new Utils.PhException("请提供学校编号");
            if (db != null)
            {
                if (db.DataContext.Classes.Any(p => p.GradeCode == cm.GradeCode && p.School.Guid == cm.SchoolGuid && p.CIndex == cm.CIndex && p.Guid != cm.Guid))
                    throw new Utils.PhException("班级序号重复");

                 var grade = db.DataContext.Grades.FirstOrDefault(p => p.Code == cm.GradeCode);
                if (grade==null)
                    throw new Utils.PhException("年级代码错误");


                var school = db.DataContext.Schools.FirstOrDefault(p => p.Guid == cm.SchoolGuid);
                if (school == null)
                    throw new Utils.PhException("学校编号不正确");
                else
                {
                    cm.SchoolID = school.ID;
                    if (!(new int[] { 4, 9, 11 }).Contains(school.SchType))
                        cm.ClassName = string.Format("{0}{1}班", grade.GradeName, cm.CIndex);
                    else
                    {
                        if (string.IsNullOrEmpty(cm.ClassName))
                            throw new Utils.PhException("请提供班级名称");
                    }
                }
            }
        }

        public static ClassModel CreateNewClass(ClassModel model)
        {
            if (model != null)
            {
                model.CreatedOn = DateTime.Now;
                model.Guid = Guid.NewGuid();
                model.Chinese = true;
                using (DBCentre db = new DBCentre())
                {
                    SaveCheck(model, db);
                    if (model.SchoolGuid == Guid.Empty)
                        throw new Utils.PhException("未知的学校");
                    
                    
                    var dClass = Convertor.ConvertFrom<Class, ClassModel>(model);
                    db.DataContext.Classes.Add(dClass);
                    db.DataContext.SaveChanges();
                    model.ID = dClass.ID;
                    return model;
                }
            }
            return null;
        }

        public static void UpdateClass(ClassModel model)
        {
            if (model != null && model.Guid!=Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dClass = db.DataContext.Classes.FirstOrDefault(p => p.Guid==model.Guid);
                    if (dClass != null)
                    {
                        SaveCheck(model, db);
                        if (model.GradeCode != dClass.GradeCode)
                        {
                            var lst = dClass.Students.ToList();
                            lst.ForEach(p => { p.GradeCode = model.GradeCode; });
                        }//如果修改了班级的年级信息，则相关的学生记录中也要修改。
                        if (!dClass.Chinese)
                            model.ClassName = dClass.ClassName;
                        Convertor.UpdateValue(model, dClass);
                        db.DataContext.SaveChanges();
                    }
                    else
                        throw new Utils.PhException("不存在的班级");
                }
            }
        }

        public static void DeleteClass(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var cla = db.DataContext.Classes.FirstOrDefault(p => p.Guid == guid);
                    if (cla == null)
                        throw new Utils.PhException("不存在的班级编号");
                    if (cla.Students.Count>0)
                        throw new Utils.PhException("此班级内还有学生，不能删除");
                    if (!cla.Chinese)
                        throw new Utils.PhException("不能删除外籍班级。");
                    db.DataContext.Classes.Remove(cla);
                    db.DataContext.SaveChanges();
                }
            }
        }

        public static ClassModel GetClass(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var dClass = db.DataContext.Classes.FirstOrDefault(p => p.Guid == guid);
                    if (dClass != null)
                    {
                        var model = Convertor.ConvertTo<ClassModel, Class>(dClass);
                        return model;
                    }
                }
            }
            return null;
        }

        public static ClassCollection GetClasses(ClassQuery search)
        {
            var result = new ClassCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Class> q = db.DataContext.Classes;
                if (search!=null)
                {
                    if (search.SchoolID > 0)
                        q = q.Where(p => p.SchoolID == search.SchoolID);
                    if (search.SchoolGuid != Guid.Empty)
                        q = q.Where(p => p.School.Guid == search.SchoolGuid);
                    if (!string.IsNullOrEmpty(search.Key))
                        q = q.Where(p => p.ClassName.Contains(search.Key));
                }
                var n = q.Count();

                if (n > 0)
                {
                    q = q.OrderBy(p => p.GradeCode).ThenBy(p => p.CIndex);
                    if (search != null && search.PageSize > 0)
                        q = q.Skip(search.PageSize * search.PageIndex).Take(search.PageSize);
                    var lst = q.ToList();
                    result = Convertor.ConvertCollection<ClassModel, Class, ClassCollection>(lst);

                    #region 取年级信息
                    if (search!=null)
                    {
                        List<Grade> grades = null;
                        foreach (var cla in result)
                        {
                            if (search.GetGradeName) { 
                                if (grades==null)
                                    grades = db.DataContext.Grades.ToList();
                                cla.GradeName = grades.FirstOrDefault(p => p.Code == cla.GradeCode).GradeName;
                            }
                                
                            if (search.GetPersonCount)
                            {
                                var dClass = lst.Find(p => p.ID == cla.ID);
                                cla.PersonCount = dClass.Students.Count;
                            }
                        }
                    }
                     
                    #endregion
                    result.TotalRecordsCount = n;
                }
            }
            return result;
        }

        public static void CreateForignClass(Guid schGuid)
        {
            if (schGuid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var sch = db.DataContext.Schools.FirstOrDefault(p => p.Guid == schGuid);
                    if (sch != null)
                    {
                        var schType = sch.SchoolType;
                        for (var i = schType.MinGrade; i <= schType.MaxGrade; i++)
                        {
                            var grade = db.DataContext.Grades.FirstOrDefault(p => p.Code == i);
                            if (grade != null)
                            {
                                if (!db.DataContext.Classes.Any(p => !p.Chinese && p.SchoolID == sch.ID && p.GradeCode == i))
                                {

                                    var dClass = new Class()
                                    {
                                        Guid = Guid.NewGuid(),
                                        CreatedOn = DateTime.Now,
                                        SchoolID = sch.ID,
                                        Chinese = false,
                                        CIndex = 99,
                                        GradeCode = i,
                                        ClassName = string.Format("{0}(外籍)班", grade.GradeName)
                                    };
                                    db.DataContext.Classes.Add(dClass);
                                }
                            }
                        }
                        db.DataContext.SaveChanges();
                    }
                }
            }
        }
    }
}
